﻿// StrbInstruction.cs
// Contains a classs for a strb instruction

using System;


namespace armsim
{
    /// <summary>
    /// Class for an Arm STRB Instruction
    /// </summary>
    public class StrbInstruction : LoadStoreInstruction
    {
        /// <summary>
        /// Intializes a new STRB Instruction
        /// </summary>
        /// <param name="instruction">Grabs info from here</param>
        public StrbInstruction(uint instruction)
            : base(instruction)
        {

        }

        /// <summary>
        /// Executes the instruction
        /// </summary>
        /// <param name="cpu">Executes from the cpu and stores the results in the cpu</param>
        public override void Execute(VirtualCPU cpu)
        {
            var rn = cpu.Registers.ReadRegistersDuringExecute(VirtualMemory.MapRegNoToRegMem(this.Rn));
            var offset = this.Offset.ComputeOffset(cpu);
            var rd = cpu.Registers.ReadRegistersDuringExecute(VirtualMemory.MapRegNoToRegMem(this.Rd));

            var rdleastsigByte = (byte)VirtualMemory.ExtractBits(rd, 0, 7);

            var effectiveAddress = this.U == 1u ? rn + offset : rn - offset;


            cpu.RAM.WriteByte(effectiveAddress, rdleastsigByte);
        }

        /// <summary>
        /// Converts the instruction to assembly code
        /// </summary>
        /// <param name="cpu">grabs info from here</param>
        /// <returns>the assembly code</returns>
        public override string ToAssembly(VirtualCPU cpu)
        {
            return String.Format("STRB {0}", base.ToAssembly(cpu));
        }


    }
}
